package com.tsing.common.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.tsing.common.annotations.NotToken;
import com.tsing.common.exceptions.BusinessException;
import com.tsing.common.exceptions.CommonException;
import com.tsing.common.service.UserRedisService;
import com.tsing.common.utils.FilterMapUtil;
import com.tsing.common.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    UserRedisService userRedisService;

    @Value("${frame.jwt.support:false}")
    String frameSupport;

    @Autowired
    JwtConfigProp jwtConfigProp;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!"true".equals(frameSupport)) {
            return true;
        }
        Map<String, String> filterChainDefinition = jwtConfigProp.getfilterChainDefinitionMap();
        if (FilterMapUtil.wildcardMatchMapKey(filterChainDefinition, request.getServletPath(), "ign")) {
            return true;
        }
        String token = request.getHeader("token");// 从http请求头中取出
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        Method method = ((HandlerMethod) handler).getMethod();
        // 检查是否有NotToken注释，有则跳过认证
        if (method.isAnnotationPresent(NotToken.class)) {
            NotToken passToken = method.getAnnotation(NotToken.class);
            if (passToken.required()) {
                return true;
            }
        } else {// 正常情况，不需要认证的少数，如果不配置不认证，那么默认需要认证
            // 执行认证
            if (token == null) {
                throw new BusinessException(CommonException.Proxy.TOKEN_IS_REQUIRED);
            }
            // 获取token中的user id
            String userId;
            try {
                userId = JWT.decode(token).getAudience().get(0);
            } catch (JWTDecodeException j) {
                throw new BusinessException(CommonException.Proxy.TOKEN_VERIFY_ERROR);
            }
            UserVo userVo = userRedisService.getUserByToken(token);
            if (null == userVo || !userId.startsWith(userVo.getId())) {
                throw new BusinessException(CommonException.Proxy.TOKEN_USER_NOT_EXIST);
            }
            // 验证token
            try {
                userRedisService.saveUserToken2Redis(userVo);
                userRedisService.saveUser2Redis(userVo);
            } catch (JWTVerificationException e) {
                throw new BusinessException(CommonException.Proxy.TOKEN_VERIFY_ERROR);
            }
            return true;
        }
        return true;
    }

}
